package com.techvision.ip2regionproject.configuration;

import com.techvision.ip2regionproject.properties.Ip2RegionProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
@Configuration
@EnableConfigurationProperties({Ip2RegionProperties.class})
@ConditionalOnClass({Searcher.class})
public class Ip2RegionAutoConfiguration {
    @Bean(
            name = {"ip2regionSearcher"}
    )
    @ConditionalOnProperty(
            prefix = "ip2region",
            name = {"enabled"},
            havingValue = "true"
    )
    public Searcher autoIp2regionSearcher(@Autowired Ip2RegionProperties properties) {
        ClassPathResource resource = new ClassPathResource(properties.getDbFile());
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] dbBytes = IOUtils.toByteArray(inputStream); // 读取所有字节
            log.info("autoIp2regionSearcher: dbFilePath = {}", properties.getDbFile());
            return Searcher.newWithBuffer(dbBytes);
        } catch (FileNotFoundException fileNotFoundException) {
            log.error("autoIp2regionSearcher can not find db file in the path [{}], error-trace:", properties.getDbFile()
                    , fileNotFoundException);
        } catch (IOException ioException) {
            log.error("autoIp2regionSearcher createTempFile fail: [{}], error-trace:", properties.getDbFile(), ioException);
            throw new RuntimeException(ioException);
        }
        return null;
    }
}
